package com.weipai.springboot.util;

import java.security.MessageDigest;

/**
 * 信息加密算法工具
 * @author gyt
 * @date 2017年8月30日 上午11:30:02
 */
public class MessageDigestUtils {
	/**
	 * 将密码先进行sha1加密，然后再md5加密
	 * @return pwd 明文
	 */
	public static String decodeForPassWord(String pwd){
		return ciphertextForMD5( pwd);
	}

	/**
	 * 生成SHA1算法密文
	 * @return
	 */
    public static String ciphertextForSHA1(String plaintext) {
        return encode("sha1", plaintext);
    }
    
    // 计算并获取md5值
    public static String ciphertextForMD5(String plaintext) {
        return encode("md5", plaintext);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
